package com.jzy.controller.admin;

import com.jzy.constant.WebConstant;
import com.jzy.controller.BaseController;
import com.jzy.dto.LogActions;
import com.jzy.entity.Bo.RestResponseBo;
import com.jzy.entity.Vo.UserVo;
import com.jzy.exception.TipException;
import com.jzy.service.ILogService;
import com.jzy.service.IUserService;
import com.jzy.util.Commons;
import com.jzy.util.TaleUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 管理员登录/登出
 */
@Controller
@RequestMapping("/admin")
@Transactional(rollbackFor = TipException.class)
public class UserController extends BaseController {

    private static final Logger LOGGER = LoggerFactory.getLogger(UserController.class);

    @Resource
    private IUserService userService;

    @Resource
    private ILogService logService;

    @GetMapping(value = "/login")
    public String login() {
        return "admin/login";
    }

    /**
     * 管理后台登录
     * @param username
     * @param password
     * @param rememberMe
     * @param session
     * @param response
     * @return
     */
    @PostMapping(value = "login")
    @ResponseBody
    public RestResponseBo doLogin(String username, String password, String rememberMe, HttpSession session, HttpServletResponse response , HttpServletRequest request){
        //登录错误 次数
        Integer error_count = cache.get("login_error_count");
        //登录
        try {
            UserVo user = userService.login(username, password);
            //存入session
            session.setAttribute(WebConstant.LOGIN_SESSION_KEY, user);
            //是否记住我
            if (StringUtils.isNotBlank(rememberMe)){
                TaleUtils.setCookie(response, user.getUid());
            }
            //更新日志
            logService.insertLog(LogActions.LOGIN.getAction(), null, request.getRemoteAddr(), user.getUid());
        } catch (Exception e) {
            error_count = null == error_count ? 1 : error_count + 1;
            //三次失败 禁止登录
            if (error_count > 3) {
                return RestResponseBo.fail("您输入密码已经错误超过3次，请10分钟后尝试");
            }
            cache.set("login_error_count", error_count, 10 * 60);
            String msg = "登录失败";
            if (e instanceof TipException) {
                msg = e.getMessage();
            }else {
                LOGGER.error(msg, e);
            }
            return RestResponseBo.fail(msg);
        }
        return RestResponseBo.ok();
    }

    /**
     * 注销
     * @param session
     * @param response
     */
    @RequestMapping("/logout")
    public void logout(HttpSession session, HttpServletResponse response, HttpServletRequest request) {
        //清除session 和 cookie
        session.removeAttribute(WebConstant.LOGIN_SESSION_KEY);
        Cookie cookie = new Cookie(WebConstant.USER_IN_COOKIE, null);
        cookie.setMaxAge(0);
        cookie.setPath("/");
        response.addCookie(cookie);
        try {
            //response.sendRedirect(Commons.site_url());
            response.sendRedirect(Commons.site_login());
        } catch (IOException e) {
            e.printStackTrace();
            LOGGER.error("注销失败", e);
        }
    }
}
